package com.shanghai.shanghaielectric.UI;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shanghai.shanghaielectric.Constants;
import com.shanghai.shanghaielectric.DB.LitePalHelper;
import com.shanghai.shanghaielectric.DataAdapter.Cells2ShowAdapter;
import com.shanghai.shanghaielectric.Model.DeviceState;
import com.shanghai.shanghaielectric.Model.ReceiveDataModel;
import com.shanghai.shanghaielectric.R;
import com.shanghai.shanghaielectric.UI.DilaogView.Dialog_Alert;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import shanghaielectric_lib.Communication.CommunicateManager;
import shanghaielectric_lib.MyEventBus.EventBus_int_bool;
import shanghaielectric_lib.MyEventBus.EventBus_showCells;
import shanghaielectric_lib.RDBHelper.Cell_show;
import shanghaielectric_lib.Utils.LogUtil;


/**
 * 监测-基本界面
 */
public class MonitorBasicFragment extends Fragment {
    public Context mContext;
    public View monitorBasicView;
    private TextView mActiveTv;//功率
    private TextView mRectiveTv;//无功功率
    private TextView mFactorTv;//功率因数

    Unbinder unbinder;
    List<Button> buttonList;
    Cells2ShowAdapter cells2ShowAdapter;
    @BindView(R.id.grid_voltage_value_a)
    TextView gridVoltageValueA;
    @BindView(R.id.grid_voltage_value_b)
    TextView gridVoltageValueB;
    @BindView(R.id.grid_voltage_value_c)
    TextView gridVoltageValueC;
    @BindView(R.id.grid_current_value_a)
    TextView gridCurrentValueA;
    @BindView(R.id.grid_current_value_b)
    TextView gridCurrentValueB;
    @BindView(R.id.grid_current_value_c)
    TextView gridCurrentValueC;
    @BindView(R.id.grid_current_thd_a)
    TextView gridCurrentThdA;
    @BindView(R.id.grid_current_thd_b)
    TextView gridCurrentThdB;
    @BindView(R.id.grid_current_thd_c)
    TextView gridCurrentThdC;
    @BindView(R.id.powor_current_factor_a)
    TextView poworCurrentFactorA;
    @BindView(R.id.powor_current_factor_b)
    TextView poworCurrentFactorB;
    @BindView(R.id.powor_current_factor_c)
    TextView poworCurrentFactorC;
    @BindView(R.id.load_current_value_a)
    TextView loadCurrentValueA;
    @BindView(R.id.load_current_value_b)
    TextView loadCurrentValueB;
    @BindView(R.id.load_current_value_c)
    TextView loadCurrentValueC;
    @BindView(R.id.load_current_thd_a)
    TextView loadCurrentThdA;
    @BindView(R.id.load_current_thd_b)
    TextView loadCurrentThdB;
    @BindView(R.id.load_current_thd_c)
    TextView loadCurrentThdC;
    @BindView(R.id.load_power_factor_a)
    TextView loadPowerFactorA;
    @BindView(R.id.load_power_factor_b)
    TextView loadPowerFactorB;
    @BindView(R.id.load_power_factor_c)
    TextView loadPowerFactorC;
    @BindView(R.id.grid_active_power_a)
    TextView gridActivePowerA;
    @BindView(R.id.grid_active_power_b)
    TextView gridActivePowerB;
    @BindView(R.id.grid_active_power_c)
    TextView gridActivePowerC;
    @BindView(R.id.grid_reactive_power_a)
    TextView gridReactivePowerA;
    @BindView(R.id.grid_reactive_power_b)
    TextView gridReactivePowerB;
    @BindView(R.id.grid_reactive_power_c)
    TextView gridReactivePowerC;
    @BindView(R.id.grid_PF_a)
    TextView gridPFA;
    @BindView(R.id.grid_PF_b)
    TextView gridPFB;
    @BindView(R.id.grid_PF_c)
    TextView gridPFC;
    @BindView(R.id.grid_all_PF)
    TextView gridAllPF;
    @BindView(R.id.frequency)
    TextView frequency;
    @BindView(R.id.equipment_current_value_a)
    TextView equipmentCurrentValueA;
    @BindView(R.id.equipment_current_value_b)
    TextView equipmentCurrentValueB;
    @BindView(R.id.equipment_current_value_c)
    TextView equipmentCurrentValueC;
    @BindView(R.id.equipment_current_loadrate_a)
    TextView equipmentCurrentLoadrateA;
    @BindView(R.id.equipment_current_loadrate_b)
    TextView equipmentCurrentLoadrateB;
    @BindView(R.id.equipment_current_loadrate_c)
    TextView equipmentCurrentLoadrateC;
    @BindView(R.id.all_activepower)
    TextView allActivepower;
    @BindView(R.id.all_reactivepower)
    TextView allReactivepower;
    @BindView(R.id.textView3)
    TextView textView3;
    @BindView(R.id.textView4)
    TextView textView4;
    @BindView(R.id.unite_fj_Light_1)
    View uniteFjLight1;
    @BindView(R.id.unite_fj_Light_2)
    View uniteFjLight2;
    @BindView(R.id.unite_fj_Light_3)
    View uniteFjLight3;
    @BindView(R.id.unite_fj_Light_4)
    View uniteFjLight4;
    @BindView(R.id.unite_fj_Light_5)
    View uniteFjLight5;
    @BindView(R.id.unite_fj_Light_6)
    View uniteFjLight6;
    @BindView(R.id.unite_fj_Light_7)
    View uniteFjLight7;
    @BindView(R.id.unite_fj_Light_8)
    View uniteFjLight8;
    @BindView(R.id.left)
    LinearLayout left;
    @BindView(R.id.home_uniteLight_1)
    View uniteLight1;
    @BindView(R.id.bt_home_unit_1)
    Button btHomeUnit1;
    @BindView(R.id.home_uniteLight_2)
    View uniteLight2;
    @BindView(R.id.bt_home_unit_2)
    Button btHomeUnit2;
    @BindView(R.id.home_uniteLight_3)
    View uniteLight3;
    @BindView(R.id.bt_home_unit_3)
    Button btHomeUnit3;
    @BindView(R.id.home_uniteLight_4)
    View uniteLight4;
    @BindView(R.id.bt_home_unit_4)
    Button btHomeUnit4;
    @BindView(R.id.home_uniteLight_5)
    View uniteLight5;
    @BindView(R.id.bt_home_unit_5)
    Button btHomeUnit5;
    @BindView(R.id.home_uniteLight_6)
    View uniteLight6;
    @BindView(R.id.bt_home_unit_6)
    Button btHomeUnit6;
    @BindView(R.id.home_uniteLight_7)
    View uniteLight7;
    @BindView(R.id.bt_home_unit_7)
    Button btHomeUnit7;
    @BindView(R.id.home_uniteLight_8)
    View uniteLight8;
    @BindView(R.id.bt_home_unit_8)
    Button btHomeUnit8;
    @BindView(R.id.basicView)
    View basicView;
    Unbinder unbinder1;
    List<View> home_uniteLights;
    List<View> home_uniteFJLights;


    boolean isinit = false;//单元状态灯和button是否被初始化

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        System.out.println("MonitorBasic____onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("MonitorBasic____onCreate");
    }

    //    初始化！！！暂且屏蔽   换成SVG的onCreateContentView()
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println("MonitorBasic____onCreateView");
        monitorBasicView = inflater.inflate(R.layout.monitor_basic_fragment, container, false);
        mContext = getActivity().getApplication().getApplicationContext();
        unbinder1 = ButterKnife.bind(this, monitorBasicView);

        initView();
        initData();

        initListener();
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this, monitorBasicView);
        return monitorBasicView;
    }

    private void initData() {
        Constants.isScanState = false;
        cells2ShowAdapter = new Cells2ShowAdapter();
        CommunicateManager.sendData();//开机下发一次参数

    }

    public void initView() {
        buttonList = new ArrayList<>();
        buttonList.add(btHomeUnit1);
        buttonList.add(btHomeUnit2);
        buttonList.add(btHomeUnit3);
        buttonList.add(btHomeUnit4);
        buttonList.add(btHomeUnit5);
        buttonList.add(btHomeUnit6);
        buttonList.add(btHomeUnit7);
        buttonList.add(btHomeUnit8);
        home_uniteLights = new ArrayList<>();
        home_uniteLights.add(uniteLight1);
        home_uniteLights.add(uniteLight2);
        home_uniteLights.add(uniteLight3);
        home_uniteLights.add(uniteLight4);
        home_uniteLights.add(uniteLight5);
        home_uniteLights.add(uniteLight6);
        home_uniteLights.add(uniteLight7);
        home_uniteLights.add(uniteLight8);
        home_uniteFJLights = new ArrayList<>();
        home_uniteFJLights.add(uniteFjLight1);
        home_uniteFJLights.add(uniteFjLight2);
        home_uniteFJLights.add(uniteFjLight3);
        home_uniteFJLights.add(uniteFjLight4);
        home_uniteFJLights.add(uniteFjLight5);
        home_uniteFJLights.add(uniteFjLight6);
        home_uniteFJLights.add(uniteFjLight7);
        home_uniteFJLights.add(uniteFjLight8);

        if (!isinit) {
            DeviceState[] deviceState = Constants.deviceStates;
            for (int i = 0; i < buttonList.size(); i++) {
                if (deviceState[i].isConnect) {
                    buttonList.get(i).setEnabled(true);
                    buttonList.get(i).setBackgroundResource(R.drawable.btn_default);
                    home_uniteLights.get(i).setBackgroundResource(R.drawable.light_green);
                } else {
                    buttonList.get(i).setEnabled(false);
                    buttonList.get(i).setBackgroundResource(R.drawable.btn_gray);
                    home_uniteLights.get(i).setBackgroundResource(R.drawable.light_gray);
                }
            }
        }


    }

    public void initListener() {

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        System.out.println("MonitorBasic____onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println("MonitorBasic____onStart");
    }

    @Override
    public void onResume() {
        super.onResume();

        System.out.println("MonitorBasic____onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        System.out.println("MonitorBasic____onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println("MonitorBasic____onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        System.out.println("MonitorBasic____onDestroyView");
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        System.out.println("MonitorBasic____onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        System.out.println("MonitorBasic____onDetach");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveCellsData(EventBus_showCells eventBusShowCells) {
        Map<Integer, Cell_show> cell_showMap = eventBusShowCells.cell_showMap;

        ReceiveDataModel receiveDataModel = cells2ShowAdapter.cells2ReceiveDataModel(eventBusShowCells.cell_showMap);

        gridVoltageValueA.setText(receiveDataModel.grid_voltage_a);
        gridVoltageValueB.setText(receiveDataModel.grid_voltage_b);
        gridVoltageValueC.setText(receiveDataModel.grid_voltage_c);

        gridCurrentValueA.setText(receiveDataModel.grid_current_a);
        gridCurrentValueB.setText(receiveDataModel.grid_current_b);
        gridCurrentValueC.setText(receiveDataModel.grid_current_c);

        gridCurrentThdA.setText(receiveDataModel.grid_THD_a);
        gridCurrentThdB.setText(receiveDataModel.grid_THD_b);
        gridCurrentThdC.setText(receiveDataModel.grid_THD_c);

        gridActivePowerA.setText(receiveDataModel.grid_active_power_a);
        gridActivePowerB.setText(receiveDataModel.grid_active_power_b);
        gridActivePowerC.setText(receiveDataModel.grid_active_power_c);

        gridReactivePowerA.setText(receiveDataModel.grid_reactive_power_a);
        gridReactivePowerB.setText(receiveDataModel.grid_reactive_power_b);
        gridReactivePowerC.setText(receiveDataModel.grid_reactive_power_c);

        gridPFA.setText(receiveDataModel.grid_PF_a);
        gridPFB.setText(receiveDataModel.grid_PF_b);
        gridPFC.setText(receiveDataModel.grid_PF_c);

        loadCurrentValueA.setText(receiveDataModel.load_current_a);
        loadCurrentValueB.setText(receiveDataModel.load_current_b);
        loadCurrentValueC.setText(receiveDataModel.load_current_c);


        loadCurrentThdA.setText(receiveDataModel.load_THD_a);
        loadCurrentThdB.setText(receiveDataModel.load_THD_b);
        loadCurrentThdC.setText(receiveDataModel.load_THD_c);

        loadPowerFactorA.setText(receiveDataModel.load_power_factor_a);
        loadPowerFactorB.setText(receiveDataModel.load_power_factor_b);
        loadPowerFactorC.setText(receiveDataModel.load_power_factor_c);

        equipmentCurrentLoadrateA.setText(receiveDataModel.equipment_load_factor_a);
        equipmentCurrentLoadrateB.setText(receiveDataModel.equipment_load_factor_b);
        equipmentCurrentLoadrateC.setText(receiveDataModel.equipment_load_factor_c);

        equipmentCurrentValueA.setText(receiveDataModel.equipment_current_a);
        equipmentCurrentValueB.setText(receiveDataModel.equipment_current_b);
        equipmentCurrentValueC.setText(receiveDataModel.equipment_current_c);

        gridAllPF.setText(receiveDataModel.all_PF);
        frequency.setText(receiveDataModel.frequence);

        allActivepower.setText(receiveDataModel.all_active_power);
        allReactivepower.setText(receiveDataModel.all_reactive_power);

        for (int i = 0; i < home_uniteLights.size(); i++) {
            if (Constants.deviceStates[i].isConnect) {
                if (Constants.deviceStates[i].deviceState == DeviceState.deviceState_error) {
                    home_uniteLights.get(i).setBackgroundResource(R.drawable.light_red);
                } else {
                    home_uniteLights.get(i).setBackgroundResource(R.drawable.light_green);
                }

                if (Constants.deviceStates[i].enableState) {
                    buttonList.get(i).setBackgroundResource(R.drawable.btn_pressed);
                } else {
                    buttonList.get(i).setBackgroundResource(R.drawable.btn_default);

                }
                buttonList.get(i).setEnabled(true);
            } else {
                home_uniteLights.get(i).setBackgroundResource(R.drawable.light_gray);
                buttonList.get(i).setBackgroundResource(R.drawable.btn_gray);
                buttonList.get(i).setEnabled(false);
            }
        }
        int resourceID_FJ = receiveDataModel.unite_FJ_state ? R.drawable.light_green : R.drawable.light_gray;
        home_uniteFJLights.get(eventBusShowCells.deviceID - 1).setBackgroundResource(resourceID_FJ);
        Constants.deviceFJStates[eventBusShowCells.deviceID - 1] = receiveDataModel.unite_FJ_state;
//        LogUtil.e("basic", "" + eventBusShowCells.deviceID + "__" + eventBusShowCells.cell_showMap.get(1).showValue);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveDeviceState(EventBus_int_bool eventBusIntBool) {
        isinit = true;
//        int resourceID = eventBusIntBool.flag ? R.drawable.btn_default : R.drawable.btn_gray_radio;
//        buttonList.get(eventBusIntBool.id - 1).setBackgroundResource(resourceID);
//        buttonList.get(eventBusIntBool.id - 1).setEnabled(eventBusIntBool.flag);
        int resourceID_fj = eventBusIntBool.flag ? R.drawable.light_green : R.drawable.light_gray;
        home_uniteLights.get(eventBusIntBool.id - 1).setBackgroundResource(resourceID_fj);
        home_uniteLights.get(eventBusIntBool.id - 1).setEnabled(eventBusIntBool.flag);
//        LogUtil.e("home", "home");
    }

    @OnClick({R.id.bt_home_unit_1, R.id.bt_home_unit_2, R.id.bt_home_unit_3, R.id.bt_home_unit_4, R.id.bt_home_unit_5, R.id.bt_home_unit_6, R.id.bt_home_unit_7, R.id.bt_home_unit_8})
    public void onViewClicked(View view) {
        for (int i = 0; i < buttonList.size(); i++) {

            if (view.getId() == buttonList.get(i).getId()) {
                String content = Constants.deviceStates[i].enableState ? "取消使能" : "使能";
                showDiolg("单元" + (i + 1) + "是否" + content);
                final int finalI = i;
                Dialog_Alert.setDiolgAlertListener(new Dialog_Alert.DialogAlertListener() {
                    @Override
                    public void onClink(boolean flag) {
                        if (flag) {
                            Constants.deviceStates[finalI].enableState = !Constants.deviceStates[finalI].enableState;
                            Toast.makeText(mContext, "state..." + Constants.deviceStates[finalI].enableState, Toast.LENGTH_SHORT).show();
                            String state = "";
                            for (DeviceState deviceState : Constants.deviceStates) {
                                state = (deviceState.enableState ? "1" : "0") + state;
                            }
                            Constants.writeDataModel.unitEnable = Integer.parseInt(state, 2);

                            LogUtil.e("enable", "" + Constants.writeDataModel.unitEnable);

//                            WriteDataModel writeDataModel = Constants.writeDataModel;
                            if (Constants.deviceStates[finalI].enableState) {
                                buttonList.get(finalI).setBackgroundResource(R.drawable.btn_pressed);
//                                Toast.makeText(mContext, "单元" + finalI + "使能", Toast.LENGTH_SHORT).show();
//                                writeDataModel.setUnitEnable_index(finalI, true);
                                LitePalHelper.insertOperateInfo("单元" + finalI + "使能");
                            } else {
                                buttonList.get(finalI).setBackgroundResource(R.drawable.btn_default);
                                try {
//                                Toast.makeText(mContext, "单元" + finalI + "取消使能", Toast.LENGTH_SHORT).show();
//                                    LogUtil.e("enable", "" + writeDataModel.getUnitEnable());
//                                    writeDataModel.setUnitEnable_index(finalI, false);
//                                    LogUtil.e("enable", "" + writeDataModel.getUnitEnable());
                                } catch (Exception e) {
                                    LogUtil.e("enable", e.toString());
                                }
                                LitePalHelper.insertOperateInfo("单元" + finalI + "取消使能");
                            }
//                            Constants.writeDataModel=writeDataModel;
                            CommunicateManager.sendData();
                        } else {

                        }
                    }
                });

            }


        }
    }

    private void showDiolg(String commandName) {
        Dialog_Alert diolgAlert = new Dialog_Alert();
        diolgAlert.setCommandName(commandName);
        diolgAlert.show(this.getFragmentManager(), "");
    }

/*    //新增的初始化
    @Override
    protected void onCreateContentView(View contentView, Bundle savedInstanceState) {
        //新增初始化
        initViews(contentView);
    }*/

    //应该返回到主界面去monitor_basic_fragment，而不是R.layout.fragment_monitor_capacitor
/*    @Override
    protected int getLayoutResId() {
        return R.layout.monitor_basic_fragment;
    }*/


}
